/* 
 * File:   Menu_Widget.cpp
 * Author: Filipp
 * 
 * Created on June 16, 2010, 1:30 PM
 */

#include "Menu_Widget.h"

Menu_Widget::Menu_Widget(Super_Man* hero, const sf::Unicode::Text& text, bool goRight) : Text_Widget(hero, text),
		expandRight(goRight), isActive(false), lastMouseState(false){
	items.push_back(this);
	SetFonts();
	setup();
}

void Menu_Widget::update(const sf::Input& sfi, float time){
	if(Text_Widget::IsInside(sfi.GetMouseX(), sfi.GetMouseY())){
		if(lastMouseState && !sfi.IsMouseButtonDown(sf::Mouse::Left)){
			isActive=true;
		}
		else
			lastMouseState=sfi.IsMouseButtonDown(sf::Mouse::Left);
	}
	if(isActive && IsInside(sfi.GetMouseX(), sfi.GetMouseY())){
		for(size_t i=1; i<items.size(); ++i)
			items[i]->update(sfi, time);
	}
	else if(isActive){
		lastMouseState = false;
		isActive=false;
	}
}
bool Menu_Widget::IsInside(float x, float y) const{
	if(!isActive){
		return Text_Widget::IsInside(x, y);
	}
	else{
		bool inside=Text_Widget::IsInside(x, y);
		x-=GetPosition().x;
		y-=GetPosition().y;
		for(size_t i=1; i<items.size(); ++i){
			inside = inside || items[i]->IsInside(x, y);
			if(inside) break;
		}
		return inside;
	}
}
bool Menu_Widget::IsInside(const vec2f& Position) const{
	return IsInside(Position.x, Position.y);
}
bool Menu_Widget::IsInside(const sf::Vector2f& Position) const{
	return IsInside(Position.x, Position.y);
}
void Menu_Widget::RegisterWidget(Super_Widget& widget){
	items.push_back(&widget);
}
void Menu_Widget::DeregisterWidget(const Super_Widget& widget){
	for(size_t i=0; i<items.size(); ++i){
		if(items[i]==&widget){
			for(size_t j=i; j<items.size()-1; ++j){
				items[j]=items[j+1];
			}
			items.pop_back();
			--i;
		}
	}
}
void Menu_Widget::Render(sf::RenderTarget& Target) const{
	Text_Widget::Render(Target);
	if(isActive){
		for(size_t i=1; i<items.size(); ++i)
			Target.Draw(*items[i]);
	}
}



void Menu_Widget::setup(){
	float mWidth=0.f;
	for(size_t i=0; i<items.size(); ++i){
		mWidth=std::max(mWidth, items[i]->GetSize().x);
	}
	float curY = expandRight ? 0.f : GetSize().y;
	for(size_t i=1; i<items.size(); ++i){
		items[i]->SetSize(vec2f(mWidth,items[i]->GetSize().y));
		//make it be right below
		items[i]->SetY(curY);
		curY+=items[i]->GetSize().y;
		items[i]->SetX(expandRight ? GetSize().x : 0.f);
		Menu_Widget* p = dynamic_cast<Menu_Widget*>(items[i]);
		if(p){
			//this is a sub-menu that will expand. It should be set up as well
			p->expandRight=true;
			p->setup();
		}
	}
}



